
package com.kamikaze.lamg;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;

public class MovieDBHelper {
    private Context mContext;

    private SQLiteDatabase database;

    private final static String dbPath = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/lamg/mfile1";

    private static final String[] columns = new String[] {
            "_id", "title", "actress", "duration", "filesize", "introduction", "frontcover",
            "code", "purchased"
    };

    public MovieDBHelper(Context context) {
        mContext = context;
        initDB();
        database = SQLiteDatabase.openOrCreateDatabase(dbPath, null);

    }

    public ArrayList<MovieInfo> getMovieInfos() {
        return getMovieInfos(-1, -1);
    }

    public ArrayList<MovieInfo> getMovieInfos(int limit, int offset) {

        Cursor cursor = getMovieCursor(limit, offset);
        ArrayList<MovieInfo> infos = new ArrayList<MovieInfo>();
        MovieInfo movieInfo = null;
        while (cursor.moveToNext()) {
            movieInfo = buildMovieInfo(cursor);
            infos.add(movieInfo);
        }
        cursor.close();
        return infos;
    }

    public ArrayList<Bitmap> getMovieImages(int id) {
        Cursor cursor = database.query("images", new String[] {
            "image"
        }, "movie_id=" + id, null, null, null, null);
        ArrayList<Bitmap> images = new ArrayList<Bitmap>();
        byte[] data;
        Bitmap image;
        while (cursor.moveToNext()) {
            data = cursor.getBlob(0);
            image = BitmapFactory.decodeByteArray(data, 0, data.length);
            images.add(image);
        }
        cursor.close();
        return images;
    }

    private MovieInfo buildMovieInfo(Cursor cursor) {
        MovieInfo movieInfo = new MovieInfo();
        movieInfo.id = cursor.getInt(0);
        movieInfo.title = cursor.getString(1);
        movieInfo.actress = cursor.getString(2);
        movieInfo.duration = cursor.getString(3);
        movieInfo.filesize = cursor.getString(4);
        movieInfo.introduction = cursor.getString(5);
        movieInfo.frontCover = cursor.getBlob(6);
        movieInfo.code = cursor.getString(7);
        // 是否显示code，0不显示，1显示
        movieInfo.purchased = cursor.getInt(8) == 0 ? false : true;
        return movieInfo;
    }

    public int getMovieCount() {
        Cursor cursor = database.query("movie", columns, null, null, null, null, null);
        int count = cursor.getCount();
        cursor.close();
        return count;
    }

    public int getCurrentMovieOrder(int id) {
        Cursor cursor = database.query("movie", columns, "_id <= " + id, null, null, null, null);
        int count = cursor.getCount();
        cursor.close();
        return count;
    }

    public int getMoviePosition(int id) {
        Cursor cursor = database.query("movie", columns, null, null, null, null, null);
        int position = 0;
        while (cursor.moveToNext()) {
            if (cursor.getInt(0) == id) {
                position = cursor.getPosition();
                break;
            }
        }
        cursor.close();
        return position;
    }

    public Cursor getMovieCursor(int limit, int offset) {
        String where = " 1=1 ";
        if (limit != -1) {
            where += " limit " + limit;
        }
        if (offset != -1) {
            where += " offset " + offset;
        }
        Cursor cursor = database.query("movie", columns, where, null, null, null, null);
        return cursor;
    }

    public void updateMovieShow(int id, boolean purchased) {
        ContentValues values = new ContentValues();
        values.put("purchased", purchased ? 1 : 0);
        database.update("movie", values, "_id = ?", new String[] {
            "" + id
        });
    }

    /**
     * @param id
     * @return
     */
    public MovieInfo getNextMovie(int id) {

        Cursor cursor = database.query("movie", columns, "_id>? limit 1", new String[] {
            id + ""
        }, null, null, null);
        if (!cursor.moveToFirst()) {
            return null;
        }
        MovieInfo info = buildMovieInfo(cursor);
        cursor.close();
        return info;

    }

    /**
     * @param id
     * @return
     */
    public MovieInfo getPrevMovie(int id) {

        Cursor cursor = database.query("movie", columns, "_id<?", new String[] {
            id + ""
        }, null, null, " id desc limit 1");
        if (!cursor.moveToFirst()) {
            return null;
        }
        MovieInfo info = buildMovieInfo(cursor);
        cursor.close();
        return info;

    }

    public boolean isFirst() {
        boolean first = false;
        Cursor c = database.query("setting", new String[] {
            "first"
        }, null, null, null, null, null);
        if (c.moveToFirst()) {
            first = c.getInt(0) == 0 ? true : false;
        }
        c.close();
        return first;
    }

    public void notFirst() {
        ContentValues values = new ContentValues();
        values.put("first", 1);
        database.update("setting", values, null, null);
    }

    /**
     * 初始化数据库文件
     */
    private void initDB() {

        File file = new File(dbPath);
        InputStream in = mContext.getResources().openRawResource(R.raw.moives001);
        // TODO 判断是否最新版本
        Utils.copyFile(file, in, false);
    }

    public void closeDatabase() {
        database.close();
    }
}
